package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@Api("菜品管理")
@Slf4j
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    private DishService dishService;


    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("page")
    public Result<PageResult> page(DishPageQueryDTO DishPageQueryDTO) {
        PageResult pageResult = dishService.page(DishPageQueryDTO);
        return Result.success(pageResult);
    }

    @PostMapping
    public Result save(@RequestBody DishDTO DishDTO) {
        dishService.save(DishDTO);
        cleanCache(DishDTO.getCategoryId().toString());
        return Result.success();
    }

    @GetMapping("{id}")
    public Result<DishDTO> get(@PathVariable("id") Long id) {
        DishDTO DishDTO = dishService.getById(id);
        return Result.success(DishDTO);
    }

    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO) {
        dishService.update(dishDTO);
        cleanCache("dish_*");
        return Result.success();
    }

    @DeleteMapping
    public Result delete( String ids) {
        //ids以,隔开
     List<Long> idList = new ArrayList<>();
        String[] split = ids.split(",");
        for (String s : split) {
            idList.add(Long.parseLong(s));
        }
        dishService.delete(idList);
        cleanCache("dish_*");
        return Result.success();
    }

    @PostMapping("status/{status}")
    public Result updateStatus(@PathVariable("status") Integer status, Long id) {
        dishService.updateStatus(status, id);
        cleanCache("dish_*");
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> list(Integer categoryId){
        List<Dish> list = dishService.list(categoryId);
        return Result.success(list);
    }
    public void  cleanCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
        log.info("清除缓存");

    }

}
